package com.gamefx.resource
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.system.ApplicationDomain;
	import flash.system.Capabilities;
	import flash.system.LoaderContext;
	import flash.system.Security;
	import flash.system.SecurityDomain;
	import flash.utils.ByteArray;

	public class SWFLoader extends DataLoader
	{
		private var _context:LoaderContext;
		
		public function SWFLoader(urlOrRequest:*, priority:uint=1, estimatedBytes:uint=0)
		{
			super(urlOrRequest, priority, estimatedBytes);
			
			_rawContent = new Loader();
		}
		
		
		
		/**
		 * 
		 */
		private var _rawContent:Loader;

		public function get rawContent():Loader
		{
			return _rawContent;
		}
		
		
		/**
		 * 
		 */
		public function get content():DisplayObject
		{
			return _rawContent.content;
		}

		
		
		override protected function onDataComplete(event:Event, bytes:ByteArray):void
		{
			/* 避免一些安全沙箱困扰着许多人 */
			if (_context == null)
			{
				if (LoaderManager.defaultContext != null)
				{
					_context = LoaderManager.defaultContext;
					if (_isLocal)
					{
						_context.securityDomain = null;
					}
				}
				else if (!_isLocal)
				{
					_context = new LoaderContext(true, new ApplicationDomain(ApplicationDomain.currentDomain), SecurityDomain.currentDomain);
				}
			}
			
			if (Capabilities.playerType != "Desktop")
			{
				Security.allowDomain(url); 
			}
			
			_rawContent.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_completeHandler);
			_rawContent.loadBytes(bytes, _context);
		}
		
		protected function loader_completeHandler(event:Event):void
		{
			_rawContent.contentLoaderInfo.removeEventListener(Event.COMPLETE, loader_completeHandler);
			
			super.onDataComplete(event, null);
		}
	}
}